package tv_model;

import java.io.*;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import view.Emulator_tv;

public class ServerMain {
	
	static ArrayList<Communication> comClients =  new ArrayList<Communication>();
	
    private static String readFileAsString(String filePath) throws java.io.IOException{
        StringBuffer fileData = new StringBuffer(1000);
        BufferedReader reader = new BufferedReader(new FileReader(filePath));
        char[] buf = new char[1024];
        int numRead=0;
        while((numRead=reader.read(buf)) != -1){
            String readData = String.valueOf(buf, 0, numRead);
            fileData.append(readData);
            buf = new char[1024];
        }
        reader.close();
        return fileData.toString();
    }
	
	public static void main(String[] args){
		
		String tntData = null;
		try {
			tntData = readFileAsString("tnt.json");
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		
		Tv tv1 = new Tv("Tv Samsung", 1, tntData);
		Emulator_tv emulator = new Emulator_tv(tv1);
		emulator.setVisible(true);
		JmDNSService service1 = new JmDNSService(tv1);
			
		webSocket wsocket = new webSocket();
		
		int delay = 5000;   // delay for 5 sec.
		int period = 240000;  // repeat every 4 min.
		Timer timer = new Timer();

		timer.scheduleAtFixedRate(new TimerTask() {
		        public void run() {
		        	for(int i=0;i<comClients.size();i++){
		        		if(!comClients.get(i).isAlive()){
		        			comClients.remove(i);
		        			System.out.println("Client removed..."); //TODO emulator_tv
		        		}
		        	}
	        }
		    }, delay, period);
		
		try{
			wsocket.connect(Constants.PORT);
			// number of clients supported in parallel
			while(comClients.size() < Constants.MAX_CLIENT){
				Communication client = wsocket.accept(tv1);
				System.out.println("New client...");
				client.start();
				comClients.add(client);
			}
			for(int i=0;i<comClients.size();i++){
				try{
					comClients.get(i).join();		
				}catch (InterruptedException e){
					
				}
			}
			service1.close();
		}catch(IOException e){
			System.out.println("Connection problem"); //TODO afficher sur Emulator_tv
		}	
	}
}
